package com.s63.service;

import com.s63.dao.UserDao;
import com.s63.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public void add(User user) {
        userDao.save(user);
    }

    @Override
    public void del(Integer id) {
        userDao.deleteById(id);
    }

    @Override
    public void update(User user) {
        userDao.save(user);
    }

    @Override
    public User getById(Integer id) {
        return userDao.findById(id).get();
    }

    @Override
    public List<User> getAll() {
        return userDao.findAll();
    }

    @Override
    public Page<User> getPage(User user, PageRequest pageRequest) {
        if (!StringUtils.hasText(user.getAccount())) {
            user.setAccount(null);
        }
        if (!StringUtils.hasText(user.getRealName())) {
            user.setRealName(null);
        }

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("realName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("account", ExampleMatcher.GenericPropertyMatchers.exact());
        Example<User> example = Example.of(user, matcher);
        return userDao.findAll(example, pageRequest);
    }
}
